package mathgame.filehandlerimpl;

import java.io.DataOutputStream;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.*;

import mathgame.filehandler.IFileHandler;

public class ImplFileHandler implements IFileHandler {
	
	public static final String SEPARATOR = "-";
	
	@Override
	public HashMap<Integer, String> readFile() {
		FileReader file;
		HashMap<Integer, String> d = new HashMap<Integer, String>();
			try {
				file = new FileReader("highscorefile/highscore.txt");
			
			Scanner s = new Scanner(file);
			String st;
			String value;
			String key;
			while(s.hasNextLine()){
				st = s.nextLine();				
				value = st.split(SEPARATOR)[0];
				key = st.split(SEPARATOR)[1];
				Integer i = new Integer(key).intValue();
				d.put(i, value);
				}
			}
			catch (FileNotFoundException e) {
				e.printStackTrace();
				}
			return d; 
			}
	
	/*
	 * Will change when we know actual representation of the problem!
	 */
	@Override
	public ArrayList<String> readProblem(String s){
		FileReader file;
		ArrayList<String> retValue = new ArrayList<String>();
		Boolean answer = true;
		String tmpAnswer = "";
		String tmpProblem = "";
		String tmp;
		try {
			file = new FileReader(s);
			Scanner scan = new Scanner(file);
			while(scan.hasNextLine()){
				tmp = scan.nextLine();
				if(answer){
					tmpAnswer = tmp;
					answer = false;
					}
				else{
					tmpProblem = tmpProblem + "\n" + tmp;
					}			
				}
            retValue.add(tmpAnswer);
            retValue.add(tmpProblem);
			} catch (IOException e) {
			e.printStackTrace();
		}
		return retValue;
	}

	
	@Override
	public void saveFile(String s) {		
		DataOutputStream out;
		try {			
			File f = new File("highscorefile/highscore.txt");
			
			if(f.exists()){
				out = new DataOutputStream(new FileOutputStream(f, true));
				out.writeBytes("\n"+s);
				out.close();
				}
			else{
				PrintWriter newFile = new PrintWriter(new FileWriter("highscorefile/highscore.txt"));
				newFile.println(s);
				newFile.close();
			}
		} catch (IOException e) {
			e.printStackTrace();
		}		
	}


	
}